package com.example.springboot;

import javax.websocket.*;

/**
 * 声明一个 WebSocket 客户端
 * <p>
 * <p>
 *
 * @author Zhang.Z
 * @version 2025-09-21
 */
@ClientEndpoint
public class MyClientEndpoint {


    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        System.out.println("连接已打开");
    }

    @OnMessage
    public void onMessage(String message) {
        System.out.println("收到服务端消息：" + message);
    }

    @OnClose
    public void onClose(Session session, CloseReason reason) {
        System.out.println("连接关闭：" + reason);
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        throwable.printStackTrace();
    }

    // 客户端发送消息
    public void sendMessage(String message) throws Exception {
        if (session != null && session.isOpen()) {
            session.getBasicRemote().sendText(message);
        }
    }
}
